import React, { useState, useEffect, useRef } from 'react';
import { Checkbox, Button, Form, Input, Select, Col, Row, Tooltip, Table, Pagination, Modal, Radio, message, Upload } from 'antd';
import { InboxOutlined, SyncOutlined, SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined, VerticalAlignBottomOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { getListAPI, delAPI, getDetailAPI, addAPI, putAPI } from '@/api/modules/equipment/shebei';
import { addBatchAPI as jiaoyanguize_addBatchAPI, delBatchAPI as jiaoyanguize_delBatchAPI } from '@/api/modules/equipment/jiaoyanguize';
import { getDictsApi } from '@/api/modules/system/dictData';
import { download } from '@/api';
import { pageDelJump } from '@/utils';
import { checkFiles, parseFiles } from '@/utils/formats.js';
import { IshebeiType, IshebeiDetailType } from '@/type/modules/equipment/shebei';
import ColorBtn from '@/components/ColorBtn';
import { hasPermi } from '@/utils/auth';
import { IdictType } from '@/type/modules/system/sysDictData';
import './index.scss';
import { getListAPI as jiaoyankey_getListAPI } from '@/api/modules/equipment/jiaoyankey';
import { Link, useNavigate } from 'react-router-dom';
import { getAllListAPI as getAllListAPI_gongzuoleixing } from '@/api/modules/equipment/gongzuoleixing';

import useStore from '@/store';

import { SysDeptSelect } from '@/views/system/dept';
import { ShebeifenzuTableSelect } from '@/views/equipment/shebeifenzu';
import { GongzuoleixingTable2Select } from '@/views/equipment/gongzuoleixing';
import { ShebeileixingTableSelect } from '@/views/equipment/shebeileixing';

const { Dragger } = Upload;
window.globalObj.jiaoyanguize_addBatchAPI = jiaoyanguize_addBatchAPI
window.globalObj.jiaoyanguize_delBatchAPI = jiaoyanguize_delBatchAPI
const ShebeiTable2 = () => {
    const [queryForm] = Form.useForm();
    const [addEditForm] = Form.useForm();
    const [updateRuleForm] = Form.useForm();
    const { confirm } = Modal;
    const navigate = useNavigate();
    const {
        useLayoutStore: { changeSelectedKeys, defaultObjMobx },
        useRoutersStore: { dynamicRouters, directoryList },
    } = useStore();
    // 分页
    const [queryParams, setQueryParams] = useState<IshebeiType>({ pageNum: 1, pageSize: 10 });
    // 列表数据
    const [dataList, setDataList] = useState({ count: 0, rows: [] as IshebeiDetailType[] });
    // table loading
    const [loading, setLoading] = useState(true);
    // 新增编辑 model显隐
    const [isModalOpen, setIsModalOpen] = useState(false);
    // 更新设备校验规则
    const [isRuleModalOpen, setIsRuleModalOpen] = useState(false);
    // 新增编辑判断
    const [isAdd, setIsAdd] = useState(true);
    // 非单个禁用
    const [single, setSingle] = useState(true);
    // 非多个禁用
    const [multiple, setMultiple] = useState(true);
    // 保存table 选择的key
    const [selectKeys, setSelectKeys] = useState<React.Key[]>([]);
    //  table 后台使用的key
    const [rowKeys, setRowKeys] = useState('');
    // 控制搜索隐藏显示
    const [searchShow, setSearchShow] = useState(true);
    // 当前编辑的id
    const [currentId, setCurrentId] = useState<number>();
    // 当前编辑的id
    const [currentRecord, currentRecordSet] = useState<any>({});
    // 部门id
    const [deptId, deptIdSet] = useState<number>();
    // 新增修改弹窗里的部门id
    const [deptIdModal, deptIdModalSet] = useState<number>();
    // 存储已上传的文件
    const [isFiles, setIsFiles] = useState<UploadFile<any>[]>([]);
    const [gongsuoleixing, gongsuoleixingSet] = useState([]);
    useEffect(() => {
        try {
            const getDictsFn = async () => { };
            getDictsFn();
            getAllListAPI_gongzuoleixing().then((res: any) => {
                gongsuoleixingSet(res.data.result.rows);
            })
        } catch (error) { }
    }, []);

    // 查询列表
    const getList = async () => {
        try {
            const { data } = await getListAPI(queryParams);
            setDataList({ ...data.result });

            message.success('查询成功');
            setLoading(false);
        } catch (error) { }
    };

    useEffect(() => {
        getList();
    }, [queryParams]);

    // 搜索
    const searchQueryFn = () => {
        const form = queryForm.getFieldsValue();
        setQueryParams({
            pageNum: 1,
            pageSize: 10,
            ...form,
        });
    };

    // 重置
    const resetQueryFn = () => {
        queryForm.resetFields();
        setSelectKeys([]);
        setQueryParams({ pageNum: 1, pageSize: 10 });
    };

    // row-select
    const rowSelection = {
        selectedRowKeys: selectKeys,
        onChange: (selectedRowKeys: React.Key[]) => {
            if (!selectedRowKeys.length || selectedRowKeys.length > 1) {
                setSingle(true);
            } else {
                setSingle(false);
            }
            selectedRowKeys.length ? setMultiple(false) : setMultiple(true);
            setSelectKeys(selectedRowKeys);
            setRowKeys(selectedRowKeys.join(','));
        },
    };

    // 获取详情
    const handleEditForm = async (id: number) => {
        try {
            const { data } = await getDetailAPI(id);
            setCurrentId(id);
            setIsModalOpen(true);
            setIsAdd(false);
            addEditForm.setFieldsValue(data.result as unknown as IshebeiDetailType);
        } catch (error) { }
    };

    // 表单提交
    const handleFormFinish = async (values: IshebeiDetailType) => {
        let apiError = false;
        values.deviceVersion = values.deviceVersion || '';
        delete values.jiaoyanguize;
        try {
            if (isAdd) {
                await addAPI({ ...values }).then(
                    () => {
                        message.success('新增成功');
                    },
                    () => (apiError = true),
                );
            } else {
                await putAPI({ ...values, tableId: currentId }).then(
                    () => {
                        message.success('修改成功');
                    },
                    () => (apiError = true),
                );
            }
        } catch (error) { }
        if (apiError) {
            return;
        }
        setIsModalOpen(false);
        addEditForm.resetFields();
        getList();
    };
    // 更新规则弹窗确定
    const ruleModalOk = async () => {
        const { file_type, work_type } = updateRuleForm.getFieldsValue();
        const { deviceName: deviceName_ } = addEditForm.getFieldsValue();
        const { deviceName, deptId } = currentRecord
        if (!file_type) {
            message.warning('请选择设备类型');
            return false;
        }
        if (!work_type.length) {
            message.warning('请选择工作类型');
            return false;
        }
        if (!isFiles.length) {
            message.warning('请选择文件');
            return false;
        }
        const { originFileObj } = isFiles[0]
        let fileName = originFileObj.name
        fileName = fileName.replace(/\s/g, '')
        if (deviceName && deviceName != fileName) {
            message.warning(`请选择文件名为${deviceName}的文件`);
            return false;
        }
        const reader = new FileReader();
        reader.onload = function (e: any) {
            const fileContent = e.target.result;
            const resultData = parseFiles(fileContent, fileName);
            work_type.forEach(async (work_typeitem: any) => {
                // 根据设备类型和工作类型查出需要校验的key
                const { data } = await jiaoyankey_getListAPI({ pageNum: 1, pageSize: 999999, ...{ fileType: file_type, workType: work_typeitem } });
                const jiaoyankeyObj: any = data.result.rows.reduce((total: any, cur: any) => {
                    if (!total[cur.keyGroupName]) {
                        total[cur.keyGroupName] = {};
                    }
                    total[cur.keyGroupName][cur.key] = true;
                    return total;
                }, {});
                const rows: any = [];
                console.log(`jiaoyankeyObj`, jiaoyankeyObj)
                const errorRows: any = [];
                Object.keys(jiaoyankeyObj).forEach((item) => {
                    const key_group_name = item;
                    Object.keys(jiaoyankeyObj[key_group_name]).forEach((key) => {
                        const row = {
                            device_name: deviceName,
                            dept_id: deptId,
                            file_type,
                            work_type: work_typeitem,
                            key_group_name,
                            key,
                            equal: resultData[key_group_name] ? resultData[key_group_name][key] : '',
                        };
                        rows.push(row);
                        if (!resultData[key_group_name]) {
                            errorRows.push(row);
                        }
                    });
                });
                // console.log(`rows`,rows)
                console.log(`errorRows`, errorRows);
                if (errorRows.length > 0) {
                    message.error(`文件中参数不足，无法形成设备的校验规则，请检查文件内容`);
                    return;
                }
                // 用当前规则替换原先规则
                // 删除原先规则
                jiaoyanguize_delBatchAPI({ device_name: deviceName, work_type: work_typeitem }).then((res: any) => {
                    if (res.data.code === 200) {
                        jiaoyanguize_addBatchAPI(rows).then((res2: any) => {
                            console.log(`res2`, res2);
                            if (res2.data.code === 200) {
                                message.success('更新成功');
                                setIsRuleModalOpen(false);
                                updateRuleForm.resetFields();
                                setIsFiles([]);
                            }
                        });
                    }
                });
            });

        };
        reader.readAsText(originFileObj);
    };
    // 新增时增加校验规则的处理
    const ruleModalOk2 = async (cb = () => { }) => {
        const { file_type, work_type } = updateRuleForm.getFieldsValue();
        const { deviceName, deptId } = addEditForm.getFieldsValue()
        // 有一个值就校验3个值是否都有值
        if (!file_type) {
            message.warning('请选择设备类型');
            return false;
        }
        if (!work_type) {
            message.warning('请选择工作类型');
            return false;
        }
        if (!isFiles.length) {
            message.warning('请选择文件');
            return false;
        }
        const { originFileObj } = isFiles[0]
        // 根据设备类型和工作类型查出需要校验的key
        const { data } = await jiaoyankey_getListAPI({ pageNum: 1, pageSize: 999999, ...{ file_type, work_type } });
        const jiaoyankeyObj: any = data.result.rows.reduce((total: any, cur: any) => {
            total[`${cur.keyGroupName}@#${cur.key}`] = true
            return total
        }, {});
        const reader = new FileReader();
        reader.onload = function (e: any) {
            const fileContent = e.target.result;
            const resultData = parseFiles(fileContent, originFileObj.name);
            const rows: any = []
            Object.keys(jiaoyankeyObj).forEach(item => {
                const key_group_name = item.split('@#')[0]
                const key = item.split('@#')[1]
                const row = {
                    device_name: deviceName,
                    dept_id: deptId,
                    file_type,
                    work_type,
                    key,
                    equal: resultData[key],
                    key_group_name
                };
                rows.push(row)
            })
            // console.log(`rows`,rows)    
            // 用当前规则替换原先规则
            // 删除原先规则
            jiaoyanguize_delBatchAPI({ device_name: deviceName, work_type }).then((res: any) => {
                if (res.data.code === 200) {
                    jiaoyanguize_addBatchAPI(rows).then((res2: any) => {
                        console.log(`res2`, res2)
                        if (res2.data.code === 200) {
                            message.success('更新成功');
                            setIsRuleModalOpen(false);
                            updateRuleForm.resetFields();
                            setIsFiles([])
                            cb()
                        }
                    })
                }
            })
            // 添加新的规则
        };
        reader.readAsText(originFileObj);
    };
    // 更新规则表单提交
    const handleUpdateRuleFormFinish = async (values: any) => { };

    // 分页
    const onPagChange = async (pageNum: number, pageSize: number) => {
        const form = queryForm.getFieldsValue();
        setQueryParams({ pageNum, pageSize, ...form });
    };

    // 删除
    const delFn = (ids: string) => {
        confirm({
            icon: <ExclamationCircleOutlined />,
            content: `是否确认删除编号为"${ids}"的数据项？`,
            centered: true,
            async onOk() {
                try {
                    const { data } = await delAPI(ids);
                    message.success(data.message);
                    pageDelJump(dataList.count, ids, queryParams, setQueryParams);
                } catch (error) { }
            },
        });
    };

    // table
    const columns = [
        {
            title: '编码',
            dataIndex: 'index',
            key: 'index',
            align: 'center',
            render: (text, record, index) => index + 1, // 渲染序号
        },
        // {
        //     title: '部门',
        //     dataIndex: 'deptId',
        //     key: 'deptId',
        //     align: 'center',
        // },
        {
            title: '所属组名',
            dataIndex: 'groupName',
            key: 'groupName',
            align: 'center',
        },
        {
            title: '设备名称',
            dataIndex: 'deviceName',
            key: 'deviceName',
            align: 'center',
        },
        // {
        //   title: '设备版本',
        //   dataIndex: 'deviceVersion',
        //   key: 'deviceVersion',
        //   align: 'center',
        // },
        {
            title: '操作',
            key: 'operation',
            align: 'center',
            fixed: 'right',
            render: (_: any, record: IshebeiDetailType) => (
                <div>
                    {/* <Button hidden={hasPermi('equipment:shebei:edit')} onClick={() => handleEditForm(record.tableId as number)} size="small" icon={<EditOutlined />} type="link">
            修改
          </Button> */}
                    <Button hidden={hasPermi('equipment:shebei:remove')} size="small" icon={<DeleteOutlined />} type="link" onClick={() => delFn(String(record.tableId))}>
                        删除
                    </Button>
                    <Button
                        hidden={hasPermi('equipment:shebei:remove')}
                        size="small"
                        type="link"
                        onClick={() => {
                            currentRecordSet(record);
                            const { deviceName = '' } = record
                            const houzhui = deviceName.split('.')[1]
                            setIsRuleModalOpen(true);
                            // 重置弹窗数据
                            updateRuleForm.setFieldsValue({
                                'file_type': houzhui === 'bkp' ? '1代润京光CT' : '2代润京光CT'
                            })
                        }}
                    >
                        更新设备校验规则
                    </Button>
                    <Button
                        hidden={hasPermi('equipment:shebei:remove')}
                        size="small"
                        type="link"
                        onClick={() => {
                            navigate('/equipment/jiaoyanguize', { state: record });
                            // changeSelectedKeys(['/equipment/jiaoyanguize'])
                            // currentRecordSet(record);
                            // setIsRuleModalOpen(true);
                            // 重置弹窗数据
                        }}
                    >
                        查看校验规则
                    </Button>
                </div>
            ),
        },
    ] as ColumnsType<IshebeiDetailType>;

    // table 数据源
    const tableData = dataList.rows;
    const props: UploadProps = {
        name: 'file',
        multiple: false,
        accept: '.ini,.bkp',
        fileList: isFiles,
        maxCount: 1,
        beforeUpload: () => false,
        onChange: (info) => {
            // console.log(`info`,info)
            // let fileName = info.file.name
            // fileName = fileName.replace(/\s/g,'')
            // let houzhui = fileName.split('.')[1]
            // updateRuleForm.setFieldsValue({
            //     'file_type':houzhui === 'bkp' ? '1代润京光CT':'2代润京光CT',
            // })
            // addEditForm.setFieldsValue({
            //     'deviceName':fileName
            // })
            setIsFiles(info.fileList);
        },
    };
    let gongzuoleixingArr = gongsuoleixing
    if (currentRecord.deviceName && currentRecord.deviceName.indexOf('bkp') > -1){
        gongzuoleixingArr = gongzuoleixingArr.filter((item:any) => {
            return item.workTypeValue !== '2024nianjian'
        })
    }
    const updateRulesCom = (
        <div>
            <div className='notice-info'>当前选中设备为：<span className='red-color'>{currentRecord.deviceName}</span></div>
            <Form form={updateRuleForm} labelCol={{ span: 5 }} initialValues={{ work_type: gongsuoleixing.map((item: any) => item.workTypeValue) }} onFinish={handleUpdateRuleFormFinish}>
                <Form.Item label="设备类型" name="file_type" rules={[{ required: true, message: '请选择设备类型!' }]}>
                    <ShebeileixingTableSelect style={{ width: 240 }} disabled={false} placeholder="请输入设备类型" rules={[{ required: true, message: '请输入设备类型!' }]} />
                </Form.Item>
                <Form.Item label="工作类型" name="work_type" rules={[{ required: true, message: '请选择工作类型!' }]}>
                    <Checkbox.Group>
                        {
                            gongzuoleixingArr.map((item: any) => {
                                return <Checkbox value={item.workTypeValue} key={item.workTypeValue}>{item.workTypeLabel}</Checkbox>
                            })
                        }
                    </Checkbox.Group>
                </Form.Item>
            </Form>
            <Dragger {...props} height={200}>
                <p className="ant-upload-drag-icon">
                    <InboxOutlined />
                </p>
                <p className="ant-upload-text">将文件拖到此处，或点击上传</p>
            </Dragger>
            <p className="upload-tip">上传标准配置文件，读取配置文件信息，生成设备校验规则数据，生成后可以在校验规则节点查看</p>
        </div>
    )
    return (
        <div className="app-container">
            <Row gutter={16}>
                <Col span={24}>
                    <Form form={queryForm} hidden={!searchShow} layout="inline" className="leno-search">
                        <Form.Item label="站" name="deptId">
                            <SysDeptSelect
                                onChange={(v: any) => {
                                    deptIdSet(v);
                                    searchQueryFn();
                                }}
                            />
                        </Form.Item>
                        <Form.Item label="组" name="groupName">
                            <ShebeifenzuTableSelect queryParams={{ deptId }} style={{ width: 240 }} placeholder="请输入所属组名" allowClear onPressEnter={searchQueryFn} />
                        </Form.Item>
                        <Form.Item label="设备名称" name="deviceName">
                            <Input style={{ width: 240 }} placeholder="请输入设备名称" allowClear onPressEnter={searchQueryFn} />
                        </Form.Item>
                        {/* <Form.Item label="设备版本" name="deviceVersion">
                            <Input style={{ width: 240 }} placeholder="请输入设备版本" allowClear onPressEnter={searchQueryFn} />
                        </Form.Item> */}

                        <Form.Item>
                            <Button onClick={searchQueryFn} type="primary" icon={<SearchOutlined />}>
                                搜索
                            </Button>
                        </Form.Item>
                        <Form.Item>
                            <Button onClick={resetQueryFn} icon={<SyncOutlined />}>
                                重置
                            </Button>
                        </Form.Item>
                    </Form>
                    <Row gutter={16} className="mb10">
                        <Col span={16} className="leno-btn">
                            <Row gutter={8}>
                                <Col>
                                    <ColorBtn
                                        hidden={hasPermi('equipment:shebei:add')}
                                        icon={<PlusOutlined />}
                                        onClick={() => {
                                            setIsModalOpen(true);
                                            setIsAdd(true);
                                        }}
                                    >
                                        新增
                                    </ColorBtn>
                                </Col>
                                {/* <Col>
                                    <ColorBtn hidden={hasPermi('equipment:shebei:edit')} disabled={single} color="success" icon={<EditOutlined />} onClick={() => handleEditForm(Number(rowKeys))}>
                                        修改
                                    </ColorBtn>
                                </Col>
                                <Col>
                                    <ColorBtn hidden={hasPermi('equipment:shebei:remove')} onClick={() => delFn(rowKeys)} disabled={multiple} color="danger" icon={<DeleteOutlined />}>
                                        删除
                                    </ColorBtn>
                                </Col>
                                 */}
                                <Col>
                                    <ColorBtn hidden={hasPermi('equipment:shebei:export')} color="warning" icon={<VerticalAlignBottomOutlined />} onClick={() => download('/equipment/shebei/export', '设备管理', 'xlsx', { ...queryParams })}>
                                        导出
                                    </ColorBtn>
                                </Col>
                            </Row>
                        </Col>
                    </Row>
                    <div className="leno-table">
                        <Table columns={columns} dataSource={tableData} pagination={false} rowKey="tableId" size="middle" loading={loading} />
                        <Pagination className="pagination" onChange={onPagChange} total={dataList.count} showSizeChanger showQuickJumper current={queryParams.pageNum} showTotal={(total) => `共 ${total} 条`} />
                    </div>

                    {/* 更新设备校验规则 */}
                    <Modal
                        title={'更新设备校验规则'}
                        open={isRuleModalOpen}
                        onOk={() => {
                            ruleModalOk()
                        }}
                        onCancel={() => {
                            setIsRuleModalOpen(false);
                            updateRuleForm.resetFields();
                            setIsFiles([])
                        }}
                    >
                        {updateRulesCom}
                    </Modal>
                    {/* 添加 编辑 */}
                    <Modal
                        title={isAdd ? '添加设备管理' : '编辑设备管理'}
                        open={isModalOpen}
                        onOk={() => {
                            if (isAdd) {
                                addEditForm.submit()
                            }
                            const cb = isAdd ? () => { } : () => {
                                setIsModalOpen(false);
                            }
                            // ruleModalOk(cb) //更新校验规则
                        }}
                        onCancel={() => {
                            setIsModalOpen(false);

                            addEditForm.resetFields();
                        }}
                    >
                        <Form form={addEditForm} labelCol={{ span: 5 }} onFinish={handleFormFinish}>
                            <Form.Item label="站" name="deptId" hidden={false} rules={[{ required: true, message: '请选择站点!' }]}>
                                <SysDeptSelect
                                    disabled={!isAdd}
                                    onChange={(v: any) => {
                                        deptIdModalSet(v);
                                    }}
                                    placeholder="请选择站"
                                />
                            </Form.Item>
                            <Form.Item label="组" name="groupName" hidden={false} rules={[{ required: true, message: '请选择所属组!' }]}>
                                <ShebeifenzuTableSelect queryParams={{ deptId: deptIdModal }} disabled={!isAdd} placeholder="请选择所属组" />
                            </Form.Item>
                            <Form.Item label="设备名称" name="deviceName" hidden={false} rules={[{ required: true, message: '请输入设备名称!' }]}>
                                <Input placeholder="请输入设备名称" disabled={!isAdd} onChange={(e) => {
                                    const newValue = e.target.value.replace(/\s+/g, ''); // 移除所有空格
                                    addEditForm.setFieldValue('deviceName', newValue);
                                }} />
                            </Form.Item>
                            {/* <Form.Item label="设备版本" name="deviceVersion" hidden={false}>
                <Input placeholder="请输入设备版本"  disabled={!isAdd} />
              </Form.Item> */}
                            <Form.Item label="校验规则" name="jiaoyanguize" hidden={true}>
                                {updateRulesCom}
                            </Form.Item>
                        </Form>
                    </Modal>
                </Col>
            </Row>
        </div>
    );
};

export default ShebeiTable2;

let cacheData: any = []; // 缓存下拉数据，减少下组件请求接口的次数
// 当前列表的下拉选组件
export function ShebeiTable2Select(props: any) {
    const { queryParams = {}, style = {} } = props;
    const [list, listSet] = useState([]);
    useEffect(() => {
        try {
            const init = async () => {
                const { data } = await getListAPI({ pageNum: 1, pageSize: 999999, ...queryParams });
                const listData: any = data.result.rows.map((item) =>
                // 需要自己改label和value的取值
                ({
                    label: item.name,
                    value: item.fileType,
                })
                );
                cacheData = listData;
                listSet(listData);
            };
            init();
        } catch (error) { }
    }, []);
    return <Select style={{ width: 240, ...style }} placeholder="请选择" options={list} {...props} />;
}
export async function shebeiList() {
    const { data } = await getListAPI({
        pageNum: 1,
        pageSize: 999999,
        string: undefined,
    });
    return { tableName: 'shebei_table2', rows: data.result.rows };
}
